package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import com.itheima.utils.DateUtils;
import com.itheima.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Date;
import java.util.Map;

/**
 * @Author: bowen
 * @Date: 2019/6/29 15:09
 * @Description:预约
 */
@RestController
@RequestMapping("/order")
public class OrderController {

	@Reference
	OrderService orderService;

	@Autowired
	JedisPool jedisPool;

	@RequestMapping("/submit")
	public Result submit(@RequestBody Map map) {
		//1.验证码是否正确
		String code = map.get("validateCode").toString();
		String telephone = map.get("telephone").toString();
		String orderDate = map.get("orderDate").toString();
		String codeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
		if(codeInRedis == null || !codeInRedis.equals(code)){
			return new Result(false, MessageConstant.VALIDATECODE_ERROR);
		}

		//2.调用服务新增预约

		map.put("orderType", Order.ORDERTYPE_WEIXIN);
		Result result= orderService.add(map);

		//3.发送预约成功的短信
		try {
			SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE, telephone, orderDate);
		} catch (ClientException e) {
			e.printStackTrace();
		}
		return result;
	}

	@RequestMapping("/findById")
	public Result findById(String id) {
			Map map = orderService.findById(id);
			//处理日期格式
			Date orderDate = (Date) map.get("orderDate");
			try {
				map.put("orderDate",DateUtils.parseDate2String(orderDate));
			} catch (Exception e) {
				e.printStackTrace();
				return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
			}
			return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,map);
	}
}
